package com.my.es.study;

import com.alibaba.fastjson.JSON;
import com.my.interview.JsonUtils;
import com.my.util.ElasticSearchUtil;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateAction;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class HelloES {

    private static final Logger log = LoggerFactory.getLogger(HelloES.class);
    public static void main(String[] args) throws UnknownHostException, IOException {


        String type = "adventure";
        String index = "movie";

        log.error("hhhhhhh");

        /**
         * None of the configured nodes are available
         * 1）elasticsearch 是否已经启动
         * 2）elasticsearch.yml 中的cluster.name 是否正确
         * 3）端口号要用9300， 9200是给http协议用的，9300给客户端用
         */
        //连接es
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch_zhonglinxia")
                .build();
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));;
/*
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9200));*/


        System.out.println("-------------------" + client);
        //1、指定Index、Type、Id进行查询记录
        GetResponse getResponse = client.prepareGet("movie","adventure", "1").get();
        if(getResponse.isExists()){
            Map<String, Object> res = getResponse.getSourceAsMap();
            System.out.println(res.toString());
        }

        //2、插入记录
        /**
         * 有四种不同的方式来产生JSON格式的文档（document）
         *
         * 手动方式，使用原生的byte[]或者String
         * 使用Map方式，会自动转换成与之等价的JSON
         * 使用第三方库来生成序列化beans，如JackJSON、FastJSON等
         * 使用内置的帮助类XContentFactory.jsonBuilder()
         */
        Map<String, Object> map = new HashMap<>();
        map.put("name", "Pirates of the Caribbean");
        map.put("actors", Arrays.asList("Tyler", "Lucy", "Maye"));
        System.out.println(map.toString());
        IndexResponse response = client.prepareIndex(index, type)
                                        .setSource(JSON.toJSONString(map), XContentType.JSON)
                                        .get();
        System.out.println(response.toString());
        System.out.println("status: " + response.status());

        //更新
        /**
         * 1.UpdateRequest进行更新
         */
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.type("adventure");
        updateRequest.index("movie");
        updateRequest.id("1");
        updateRequest.doc(XContentFactory.jsonBuilder()
                .startObject()
                .field("name", "My Experience")
                .endObject());
        try{
            UpdateResponse updateResponse = client.update(updateRequest).get();
            System.out.println("updateResponse status is:" + updateResponse.status());
        }catch (InterruptedException e){
            e.printStackTrace();
        }catch (ExecutionException e){
            e.printStackTrace();
        }
        ElasticSearchUtil.getDocument(client, type,index,"1");

        //2.prepareUpdate 基于Script对象进行更新
        UpdateResponse updateResponse = client.prepareUpdate(index, type, "1")
                .setScript(new Script("ctx._source.actors=[\"Smile\", \"Bob\",\"Clock\",\"Lily\"]")).get();
        System.out.println("update by script result is : " + updateResponse.toString());
        ElasticSearchUtil.getDocument(client, index, type,"1");

        //3.prepareUpdate 基于XContentFactory.jsonBuilder()进行更新
        UpdateResponse updateResponse1 = client.prepareUpdate(index, type, "1")
                .setDoc(XContentFactory.jsonBuilder().startObject()
                .field("name", "My Experience Update")
                .field("actors", Arrays.asList("Smith", "Lucy", "Emily"))
                .endObject()).get();
        System.out.println("update by script result is : " + updateResponse1.toString());
        ElasticSearchUtil.getDocument(client, index, type,"1");


        Map<String, Object> map2 = new HashMap<>();
        map.put("name", "orange");
        map.put("operator", Arrays.asList("Lucy", "Bob"));
        ElasticSearchUtil.insertDocument(client, "food", "fruit", null, JSON.toJSONString(map2), null);


        //删除记录
        DeleteResponse deleteResponse = client.prepareDelete("food", "fruit", "1").get();
        System.out.println("deleteResponse is :" + deleteResponse.toString());

        //查询多条记录
        SearchResponse searchResponse = client.prepareSearch(index).setTypes(type)
                .setQuery(QueryBuilders.matchQuery("actors", "Lucy")).get();

        SearchHit[] searchHit = searchResponse.getHits().getHits();
        for(int i =0;i < searchHit.length;i++){
            System.out.println(searchHit[i].getSourceAsString());
        }
        client.close();
    }
}
